import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:enterprise_v8/app/components/custom_app_bar.dart';
import 'package:enterprise_v8/app/core/utils/log_util.dart';

/// 二维码扫描
/// [onScanResult] 扫描结果回调
/// demo:
/// ```dart
/// CustomQrScanPage(
///  onScanResult: (value) {
///      AppToast.show('扫描结果：$value');
///    },
/// );
/// ```
class CustomQrScanPage extends StatefulWidget {
  const CustomQrScanPage({required this.onScanResult, super.key});

  final Function(String) onScanResult;

  @override
  State<CustomQrScanPage> createState() => _CustomQrScanPageState();
}

class _CustomQrScanPageState extends State<CustomQrScanPage> with WidgetsBindingObserver {
  // 扫描控制器
  var controller = MobileScannerController(
    detectionSpeed: DetectionSpeed.normal,
    facing: CameraFacing.back,
  );

  // 扫描订阅
  StreamSubscription<Object?>? _subscription;

  // 扫描结果
  void _handleBarcode(BarcodeCapture result) {
    final List<Barcode> barcodes = result.barcodes;
    for (var barcode in barcodes) {
      if (barcode.displayValue != null) {
        controller.dispose();
        Get.back();
        AppLogger.log('扫描到:${barcode.displayValue}');
        widget.onScanResult(barcode.displayValue!);
      }
    }
  }

  // 扫描到的结果
  onSuccess(BarcodeCapture result) {

  }

  // 打开手电筒
  openTorch() async {
    await controller.toggleTorch();
  }

  @override
  void initState() {
    super.initState();
    // Start listening to lifecycle changes.
    WidgetsBinding.instance.addObserver(this);

    // Start listening to the barcode events.
    _subscription = controller.barcodes.listen(_handleBarcode);

    // Finally, start the scanner itself.
    unawaited(controller.start());
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
      case AppLifecycleState.paused:
        return;
      case AppLifecycleState.resumed:
        // 当应用程序恢复时，重新启动扫描仪。
        //不要忘记继续监听条形码事件。
        _subscription = controller.barcodes.listen(_handleBarcode);

        unawaited(controller.start());
      case AppLifecycleState.inactive:
        // 当应用程序暂停时，停止扫描仪。
        // 还要停止条形码事件订阅。
        unawaited(_subscription?.cancel());
        _subscription = null;
        unawaited(controller.stop());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        titleText: '二维码扫描',
        actions: [
          // 手电筒
          IconButton(
            icon: const Icon(Icons.flashlight_on),
            onPressed: openTorch,
          ),
        ],
      ),
      body: MobileScanner(
        controller: controller,
        // onDetect: onSuccess,
      ),
    );
  }

  @override
  Future<void> dispose() async {
    // 停止倾听生命周期的变化。
    WidgetsBinding.instance.removeObserver(this);
    // 停止收听条形码事件。
    unawaited(_subscription?.cancel());
    _subscription = null;
    // 处理小部件本身。
    super.dispose();
    // 最后，处理控制器。
    await controller.dispose();
  }

}
